import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:netwrok_log/errorLog/log.dart';
import 'package:netwrok_log/errorLog/log_entry.dart';
import 'package:x_custom_widget/custom_widget.dart';

// ignore: must_be_immutable
class ErrorLogPage extends StatefulWidget {
  ErrorLogPage({Key? key}) : super(key: key);

  @override
  State<ErrorLogPage> createState() => _ErrorLogPageState();
}

class _ErrorLogPageState extends State<ErrorLogPage>
    with SingleTickerProviderStateMixin {
  List data = [];
  final ScrollController _controller = ScrollController();
  int _page = 0;
  @override
  void initState() {
    getErrorLogList(0);
    _controller.addListener(() {
      if (_controller.position.maxScrollExtent <= _controller.offset) {
        getErrorLogList(_page++);
      }
    });
    super.initState();
  }

  bool isEnd = false;
  getErrorLogList(int page) {
    if (isEnd && page != 0) {
      EasyLoading.showSuccess("已加载完毕");
      return;
    }
    EasyLoading.show();
    Log().fetchErrorPagedData(page: page).then((value) {
      EasyLoading.dismiss();
      if (value.isEmpty) {
        isEnd = true;
        return;
      }
      data = [...data, ...value];
      setState(() {});
    });
  }
  // ErrorLogManager().writeLogToFile(
  //     logFileName: "errorlog", errorDetail: "errorDoc.toString()");

  // ErrorLogManager().readLogFromFile(logFileName: "errorlog").then((value) {
  //   errorDetail = value;
  //   setState(() {});
  // });

  Widget build(BuildContext context) {
    EasyLoading.dismiss();
    final logProvider = LogProvider.of(context);

    return Scaffold(
        appBar: AppBar(
          title: Text('错误日志'),
          actions: [
            GestureDetector(
                child: Icon(Icons.delete),
                onTap: () {
                  EasyLoading.show();
                  Log().cleanErrorLog().then((value) {
                    EasyLoading.dismiss();
                    data = [];
                    _page = 0;
                    isEnd = false;
                    setState(() {});
                  });
                })
          ],
        ),
        body: Container(
          padding: EdgeInsets.all(12),
          color: logProvider!.themeColor,
          child: ListView.separated(
            itemBuilder: (context, index) {
              //            "webUrl": errorData["webUrl"],
              //   "errorDoc": errorData["errorDoc"],
              //   "terminal": 'ZERODY-CRM-MINI',
              //   "errorType": 'stackTrace',
              //   "errorEnv": '${Config.env}',
              //   'time': DateTime.now().millisecondsSinceEpoch,
              // }
              String dateStr = DateFormat('yyyy-MM-dd HH:mm:ss').format(
                  DateTime.fromMillisecondsSinceEpoch(data[index]["time"]));
              return LogItem(data: data[index], dateStr: dateStr, index: index);
            },
            controller: _controller,
            itemCount: data.length,
            separatorBuilder: (BuildContext context, int index) {
              return Divider(color: Colors.white);
            },
          ),
        ));
  }
}

class LogItem extends StatefulWidget {
  const LogItem({
    Key? key,
    required this.data,
    required this.dateStr,
    required this.index,
  }) : super(key: key);
  final int index;
  final Map data;
  final String dateStr;

  @override
  State<LogItem> createState() => _LogItemState();
}

class _LogItemState extends State<LogItem> {
  bool show = false;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        show = !show;

        setState(() {});
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CustomText(
            "${widget.index}",
            color: Colors.white,
            fontSize: 30,
            fontWeight: FontWeight.w500,
            padding: EdgeInsets.only(right: 12),
          ),
          Expanded(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      CustomText("页面",
                          color: Color.fromARGB(255, 240, 141, 134)),
                      Expanded(
                          child: CustomText("\t\t${widget.data["web_url"]}",
                              fontWeight: FontWeight.w500,
                              fontSize: 15,
                              maxLines: 100,
                              color: Colors.white)),
                    ],
                  ),
                  CustomText("\t\t${widget.dateStr}",
                      fontWeight: FontWeight.w500,
                      fontSize: 12,
                      color: Colors.white),
                  CustomText(
                    "\t\t${widget.data["error_doc"]}",
                    maxLines: show ? 1000 : 5,
                    color: Colors.white,
                  ),
                ]),
          ),
        ],
      ),
    );
  }
}
